#include <stdio.h>
#include <stdlib.h>
#include "dominion.h"
#include "dominion_helpers.h"
#include "rngs.h"

//This Unit Test Will Test the isGameOver() Function.

//initialize game struct to array of 0's
void clearGameState(struct gameState *G) {
  int i;
	for (i=0; i<sizeof(struct gameState); i++) {
		((char *)G)[i] = 0;
	}
}

int main() {	

	int i, j, a, b;
	int numPlayers;	//relevant to scoreFor() in dominion.c
	int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy};
	int seed = 103;				//FEEL FREE TO CHANGE
	int num_tests = 100;		//FEEL FREE TO CHANGE
	int errors = 0;
	struct gameState G;
	
	//initialize random number using rngs.c library
	SelectStream(1);
	PutSeed((long)seed);
	
	printf("Now Testing unittest 4: isGameOver() Function\n");
	
	for (i=0; i < num_tests; i++) {
	  
	  clearGameState(&G);					//blank the game state
	  
	  numPlayers = (int)(Random()*2)+2;		//gets random number of players >=2
	
	  //initialize a game with random number of players
	  initializeGame(numPlayers, k, seed, &G);	
	  
	  //verify the game doesn't return over immediately
	  if (isGameOver(&G)) {
		printf("Error: The game is over after being initialized\n");
		errors++;
	  }
	  
	  //verify the game returns being over if the number of province cards is empty
	  G.supplyCount[province] = 0;
	  if (!isGameOver(&G)) {
		printf("Error: There are %d province cards and the game is not over.\n", G.supplyCount[province]);
		errors++;
	  }
	  
	  //put number of province cards back at non-zero.
	  G.supplyCount[province] = 5;
	  
	  //Make sure the game ends when three of the supplyCounts are zero. This will make 3 supply counts equal to zero.
	  for (j=0; j<3; j++) {
		a = (int)(Random()*25);		//there are 25 cards in dominion.
		
		if (G.supplyCount[a] != 0) {
			G.supplyCount[a] = 0;
		}
	  }
	  
	  //verify game ends with three supply counts equal to zero.
	  if (!isGameOver(&G)) {
		printf("Error: The game did not properly end when three supply counts were zero. Here are the supply counts:\n");
		for (b=0; b<25; b++) {
			printf("SupplyCount of supplyCount[%d]: %d", b, G.supplyCount[b]);
		}
		errors++;
	  }
	} // end main loop
	
	printf("Out of %d tests, there were %d errors\n\n", num_tests, errors);

	return 0;
}

/*For Reference

int isGameOver(struct gameState *state) {
  int i;
  int j;
	
  //if stack of Province cards is empty, the game ends
  if (state->supplyCount[province] == 0)
    {
      return 1;
    }

  //if three supply pile are at 0, the game ends
  j = 0;
  for (i = 0; i < 25; i++)
    {
      if (state->supplyCount[i] == 0)
	{
	  j++;
	}
    }
  if ( j >= 3)
    {
      return 1;
    }

  return 0;
}

*/